<template>
  <a-modal
    :open="visible"
    title="编辑图片信息"
    width="600px"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <template #footer>
      <a-space>
        <a-popconfirm
          title="确定要删除这张图片吗？"
          ok-text="确定"
          cancel-text="取消"
          @confirm="handleDelete"
        >
          <a-button type="primary" danger :loading="deleteLoading"> 删除图片 </a-button>
        </a-popconfirm>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="loading" @click="handleSubmit"> 确定 </a-button>
      </a-space>
    </template>
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" @finish="handleFinish">
      <!-- 图片预览 -->
      <div class="picture-preview-section">
        <a-image
          :src="pictureData?.thumbnailUrl || pictureData?.url"
          :alt="pictureData?.name"
          :width="120"
          :height="120"
          style="object-fit: cover; border-radius: 8px"
          :preview="{ src: pictureData?.url }"
        />
        <div class="picture-basic-info">
          <h4>{{ pictureData?.name }}</h4>
          <p class="picture-meta">
            {{ formatFileSize(pictureData?.picSize) }} • {{ pictureData?.picWidth }}×{{
              pictureData?.picHeight
            }}
            •
            {{ pictureData?.picFormat?.toUpperCase() }}
          </p>
        </div>
      </div>

      <a-divider />

      <!-- 编辑表单 -->
      <a-form-item
        label="图片名称"
        name="name"
        :rules="[{ required: true, message: '请输入图片名称' }]"
      >
        <a-input
          v-model:value="formData.name"
          placeholder="请输入图片名称"
          :maxlength="100"
          show-count
        />
      </a-form-item>

      <a-form-item label="图片简介" name="introduction">
        <a-textarea
          v-model:value="formData.introduction"
          placeholder="请输入图片简介"
          :rows="3"
          :maxlength="500"
          show-count
        />
      </a-form-item>

      <a-form-item label="图片分类" name="category">
        <a-auto-complete
          v-model:value="formData.category"
          :options="categoryOptions"
          placeholder="请选择或输入分类"
          :filter-option="filterOption"
        />
      </a-form-item>

      <a-form-item label="图片标签" name="tags">
        <a-select
          v-model:value="formData.tags"
          mode="tags"
          placeholder="请输入标签，按回车添加"
          :options="tagOptions"
          :max-tag-count="10"
          :max-tag-text-length="20"
        >
          <template #tagRender="{ label, closable, onClose }">
            <a-tag :closable="closable" style="margin-right: 4px" @close="onClose">
              <template #icon><TagOutlined /></template>
              {{ label }}
            </a-tag>
          </template>
        </a-select>
        <div class="form-help">
          <a-typography-text type="secondary" style="font-size: 12px">
            可以输入自定义标签，也可以从推荐标签中选择
          </a-typography-text>
        </div>
      </a-form-item>
    </a-form>

    <!-- 推荐标签 -->
    <div class="recommended-tags" v-if="recommendedTags.length > 0">
      <h5>推荐标签</h5>
      <div class="tags-list">
        <a-tag
          v-for="tag in recommendedTags"
          :key="tag"
          :color="formData.tags.includes(tag) ? 'blue' : ''"
          style="margin: 4px; cursor: pointer"
          @click="toggleTag(tag)"
        >
          <template #icon><TagOutlined /></template>
          {{ tag }}
        </a-tag>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { TagOutlined } from '@ant-design/icons-vue'
import { updatePicture, listPictureTagCategory, deletePicture } from '@/api/picture'
import type {
  Picture,
  PictureUpdateRequest,
  PictureTagCategory,
  DeleteRequest,
} from '@/types/picture'
import type { FormInstance } from 'ant-design-vue'

interface Props {
  visible: boolean
  pictureData: Picture | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const deleteLoading = ref(false)
const formRef = ref<FormInstance>()
const tagCategoryData = ref<PictureTagCategory>()

// 表单数据
const formData = reactive<PictureUpdateRequest & { tags: string[] }>({
  id: '0',
  name: '',
  introduction: '',
  category: '',
  tags: [],
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入图片名称' },
    { max: 100, message: '图片名称不能超过100个字符' },
  ],
  introduction: [{ max: 500, message: '图片简介不能超过500个字符' }],
  category: [{ max: 50, message: '分类名称不能超过50个字符' }],
}

// 计算属性
const categoryOptions = computed(() => {
  if (!tagCategoryData.value?.categoryList) return []
  return tagCategoryData.value.categoryList.map((category) => ({
    value: category,
    label: category,
  }))
})

const tagOptions = computed(() => {
  if (!tagCategoryData.value?.tagList) return []
  return tagCategoryData.value.tagList.map((tag) => ({
    value: tag,
    label: tag,
  }))
})

const recommendedTags = computed(() => {
  if (!tagCategoryData.value?.tagList) return []
  return tagCategoryData.value.tagList.slice(0, 20) // 显示前20个推荐标签
})

// 监听弹窗显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal && props.pictureData) {
      resetForm()
      loadFormData()
    }
  },
)

// 加载表单数据
const loadFormData = () => {
  if (!props.pictureData) return

  formData.id = props.pictureData.id
  formData.name = props.pictureData.name || ''
  formData.introduction = props.pictureData.introduction || ''
  formData.category = props.pictureData.category || ''

  // 处理标签数据
  if (props.pictureData.tags) {
    if (typeof props.pictureData.tags === 'string') {
      try {
        const parsed = JSON.parse(props.pictureData.tags)
        formData.tags = Array.isArray(parsed) ? parsed : [props.pictureData.tags]
      } catch {
        formData.tags = props.pictureData.tags
          .split(',')
          .map((tag) => tag.trim())
          .filter((tag) => tag)
      }
    } else {
      formData.tags = [...props.pictureData.tags]
    }
  } else {
    formData.tags = []
  }
}

// 重置表单
const resetForm = () => {
  formData.id = '0'
  formData.name = ''
  formData.introduction = ''
  formData.category = ''
  formData.tags = []
  formRef.value?.resetFields()
}

// 获取标签和分类数据
const fetchTagCategoryData = async () => {
  try {
    const response = await listPictureTagCategory()
    tagCategoryData.value = response.data
  } catch (error) {
    console.error('获取标签分类数据失败:', error)
  }
}

// 分类筛选
const filterOption = (input: string, option: { label: string }) => {
  return option.label.toLowerCase().includes(input.toLowerCase())
}

// 切换标签选中状态
const toggleTag = (tag: string) => {
  const index = formData.tags.indexOf(tag)
  if (index > -1) {
    formData.tags.splice(index, 1)
  } else {
    formData.tags.push(tag)
  }
}

// 处理提交
const handleSubmit = () => {
  formRef.value
    ?.validateFields()
    .then(() => {
      handleFinish()
    })
    .catch(() => {
      // 验证失败，不做任何处理
    })
}

// 表单提交
const handleFinish = async () => {
  try {
    loading.value = true

    const updateData: PictureUpdateRequest = {
      id: formData.id,
      name: formData.name?.trim() || '',
      introduction: formData.introduction?.trim() || undefined,
      category: formData.category?.trim() || undefined,
      tags: formData.tags && formData.tags.length > 0 ? formData.tags : undefined,
    }

    await updatePicture(updateData)
    message.success('图片信息更新成功')
    emit('success')
    handleCancel()
  } catch (error) {
    console.error('更新图片失败:', error)
    message.error('更新图片失败')
  } finally {
    loading.value = false
  }
}

// 删除图片
const handleDelete = async () => {
  if (!props.pictureData) return

  try {
    deleteLoading.value = true
    const deleteRequest: DeleteRequest = {
      id: props.pictureData.id,
    }

    await deletePicture(deleteRequest)
    message.success('图片删除成功')
    emit('success')
    handleCancel()
  } catch (error) {
    console.error('删除图片失败:', error)
    message.error('删除图片失败')
  } finally {
    deleteLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  emit('update:visible', false)
}

// 格式化文件大小
const formatFileSize = (bytes?: number) => {
  if (!bytes) return '-'
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + ' ' + sizes[i]
}

// 组件挂载时获取数据
onMounted(() => {
  fetchTagCategoryData()
})
</script>

<style scoped>
.picture-preview-section {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.picture-basic-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.picture-meta {
  margin: 0;
  font-size: 12px;
  color: #8c8c8c;
}

.form-help {
  margin-top: 4px;
}

.recommended-tags {
  margin-top: 16px;
  padding: 16px;
  background: #f9f9f9;
  border-radius: 8px;
  border-top: 1px solid #f0f0f0;
}

.recommended-tags h5 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

:deep(.ant-select-selector) {
  min-height: 40px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 600;
}

:deep(.ant-divider) {
  margin: 16px 0;
}
</style>
